<?php

use PHPUnit\Samples\Money\Money;
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */
require_once ('XingeApp.php');
class mobileapi_rpc_order extends mobileapi_frontpage {

	var $noCache = true;

	public function __construct(&$app){
		parent::__construct($app);

		$this->app = app::get('b2c');
		$this->verify_member();

		$this->objMath = kernel::single("ectools_math");
	}

	// todo 业务此代码有互相覆盖情况，请检查新增逻辑是否需要加上，如有需要，请在git中找回，如果不会找回，请联系我
	public function create()
	{

		/**
		 * 取到扩展参数,用来判断是否是团购立即购买，团购则不判断登录（无注册购买情况下）
		 */
		$_POST['&response_json'] = true;

		$arr_args = func_get_args();
		$arr_args = array(
			'get' => $arr_args,
			'post' => $_POST,
		);

//         print_r($arr_args);exit;

		$groupbuy = (array)json_decode($arr_args['post']['extends_args']);
		// 判断顾客登录方式.
		#$login_type = $this->app->getConf('site.login_type');
		$arrMember = kernel::single('b2c_user_object')->get_current_member(); //member_id,uname
		// checkout url
//         $this->begin(array('app'=>'b2c','ctl'=>'site_cart','act'=>'checkout'));
		$db = kernel::database();
		$transaction_status = $db->beginTransaction();

		$this->mCart = $this->app->model('cart');
		if(isset($_POST['isfastbuy']) && $_POST['isfastbuy'] != 'false'){
			$is_fastbuy = 'true';
			//订单价格不进行优惠运算，增加下列三行参数。 qianjin 2016-7-11
			$fastbuy_filter['is_fastbuy'] = $is_fastbuy;
			$fastbuy_filter[0] = 'coupon';
			$fastbuy_filter['apply_platform'] = '1';
		}else{
			$is_fastbuy = false;
			//订单价格不进行优惠运算，增加下列三行参数。 qianjin 2016-7-11
			// $fastbuy_filter = true;
			$fastbuy_filter['is_fastbuy'] = $is_fastbuy;
			$fastbuy_filter[0] = 'coupon';
			$fastbuy_filter['apply_platform'] = '1';
		}
		$aCart = $this->mCart->get_objects($fastbuy_filter);
		foreach($aCart['object']['goods'] as $k=>$goods_val){
			foreach($goods_val['obj_items']['products'] as $key=>$item_val){
				if(!$item_val['price']['cost']){
					$product = app::get("b2c")->model("products")->getRow("*",array("product_id"=>$item_val['product_id']));
					$aCart['object']['goods'][$k]['obj_items']['products'][$key]['price']['cost']=$product['cost'];
				}
			}
		}
		//当有活动时，在生成订单前做一个当前购买数量与实际库存的判断
		if( isset($aCart['cart_status'] )){

			//$this->end(false,app::get('b2c')->_($aCart['cart_error_html']),$this->gen_url(array('app'=>'b2c','ctl'=>'site_cart','act'=>'index')),true,true);
			kernel::single('base_rpc_service')->send_user_error('cart_error', $aCart['cart_error_html']);
		}
		// 校验购物车是否为空
		if ($this->mCart->is_empty($aCart))
		{
			//$this->end(false,app::get('b2c')->_('操作失败，购物车为空！'),$this->gen_url(array('app'=>'b2c','ctl'=>'site_cart','act'=>'index')),true,true);
			kernel::single('base_rpc_service')->send_user_error('cart_error', '操作失败，购物车为空！');
		}
		// 校验购物车有没有发生变化
		$md5_cart_info = $_POST['md5_cart_info'];
		if (!defined("STRESS_TESTING") && $md5_cart_info != kernel::single("b2c_cart_objects")->md5_cart_objects($is_fastbuy)){
//         	$this->end(false,app::get('b2c')->_('购物车内容发生变化，请重新结算！'),$this->gen_url(array('app'=>'b2c','ctl'=>'site_cart','act'=>'checkout')),true,true);
			kernel::single('base_rpc_service')->send_user_error('cart_change_error', '购物车内容发生变化，请重新结算！');

		}

		$msg = "";
		if(!$_POST['address']){
			$msg .= app::get('b2c')->_("请先确认收货地址")."<br />";
//             $this->end(false, $msg,null,true,true);
			kernel::single('base_rpc_service')->send_user_error('order_error', $msg);
		}else{
			$address = json_decode($_POST['address'],true);
			unset($_POST['address']);
			unset($_POST['purchase']);
			$addr = $this->app->model('member_addrs')->getList('*',array('addr_id'=>$address['addr_id'],'member_id'=>$arrMember['member_id']));
			if($this->app->getConf('site.checkout.zipcode.required.open') == 'true' && empty($addr[0]['zip']) ) {
//                 $this->end(false,app::get('b2c')->_('收货地址不完整，请填写邮编'),null,true,true);
				kernel::single('base_rpc_service')->send_user_error('order_error', '收货地址不完整，请填写邮编');
			}
			$ship_area_name = app::get('ectools')->model('regions')->change_regions_data($addr[0]['area']);
			$_POST['delivery']['addr_id'] = $addr[0]['addr_id'];
			$_POST['delivery']['ship_area'] = $addr[0]['area'];
			$_POST['delivery']['ship_addr'] = $ship_area_name.$addr[0]['addr'];
			$_POST['delivery']['ship_zip'] = $addr[0]['zip'];
			$_POST['delivery']['ship_name'] = $addr[0]['name'];
			$_POST['delivery']['ship_mobile'] = $addr[0]['mobile'];
			$_POST['delivery']['ship_tel'] = $addr[0]['tel'];
			if( $this->app->getConf('site.checkout.receivermore.open') == 'true'){
				$_POST['delivery']['day'] = $addr[0]['day'];
				$_POST['delivery']['time'] = $addr[0]['time'];
			}else{
				$_POST['delivery']['day'] = app::get('b2c')->_('任意时间');
				$_POST['delivery']['time'] = app::get('b2c')->_('任意时间段');
			}
		}

		if(!$_POST['shipping']){
			$msg .= app::get('b2c')->_("请先确认配送方式")."<br />";
//             $this->end(false, $msg, '',true,true);
			kernel::single('base_rpc_service')->send_user_error('order_error', $msg);
		}else{
			//创建订单时判断配送地区是否在配送范围 by lsc 2018年3月21日12:34:27
			$shipping = json_decode($_POST['shipping'],true);
			//1配送方式
			$dlytype = app::get('b2c')->model('dlytype')->dump($shipping['id']);
			//2配送地址
			$region_id = app::get('ectools')->model('regions')->get_region_id($addr[0]['area']);
			$area_fee_conf = unserialize($dlytype['area_fee_conf']);
            if ($area_fee_conf && is_array($area_fee_conf)){
            	foreach ($area_fee_conf as $k=>$v){
            		$areas = explode(',',$v['areaGroupId']);
            		if(!in_array($region_id,$areas)){
            			kernel::single('base_rpc_service')->send_user_error('order_error', '你选择的收货地址不符合翼鸟快递配送的地区！');
            		}
            	}
            }
			unset($_POST['shipping']);
			$_POST['delivery']['shipping_id'] = $shipping['id'];
			$_POST['delivery']['is_protect'][$shipping['id']] = $_POST['is_protect'];
		}

		if(!$_POST['payment']){
			$msg .= app::get('b2c')->_("请先确认支付方式")."<br />";
			//$this->end(false, $msg, '',true,true);
			kernel::single('base_rpc_service')->send_user_error('order_error', $msg);
		}else{
			$payment_id = json_decode($_POST['payment']['pay_app_id'],true);
			$_POST['payment']['pay_app_id'] = $payment_id['pay_app_id'];
		}

		if($_POST['point']['score']){
			$score = intval($_POST['point']);
			if($score > 0){
				$_POST['payment']['dis_point'] = $score;
			}else{
				$_POST['payment']['dis_point'] = $_POST['point']['score'];
			}
		}

		if (!$_POST['delivery']['ship_area'] ||  !$_POST['delivery']['ship_addr'] || !$_POST['delivery']['ship_name'] ||  (!$_POST['delivery']['ship_mobile'] && !$_POST['delivery']['ship_tel']) || !$_POST['delivery']['shipping_id'] || !$_POST['payment']['pay_app_id'])
		{
			if (!$_POST['delivery']['ship_area'] )
			{
				$msg .= app::get('b2c')->_("收货地区不能为空！")."<br />";
			}

			if (!$_POST['delivery']['ship_addr'])
			{
				$msg .= app::get('b2c')->_("收货地址不能为空！")."<br />";
			}

			if (!$_POST['delivery']['ship_name'])
			{
				$msg .= app::get('b2c')->_("收货人姓名不能为空！")."<br />";
			}

			/*
			if (!$_POST['delivery']['ship_email'] && !$arrMember['member_id'])
			{
				$msg .= app::get('b2c')->_("Email不能为空！")."<br />";
			}
			*/

			if (!$_POST['delivery']['ship_mobile'] && !$_POST['delivery']['ship_tel'])
			{
				$msg .= app::get('b2c')->_("手机或电话必填其一！")."<br />";
			}

			if (!$_POST['delivery']['shipping_id'])
			{
				$msg .= app::get('b2c')->_("配送方式不能为空！")."<br />";
			}

			if (!$_POST['payment']['pay_app_id'])
			{
				$msg .= app::get('b2c')->_("支付方式不能为空！")."<br />";
			}

			if (strpos($msg, '<br />') !== false)
			{
				$msg = substr($msg, 0, strlen($msg) - 6);
			}
			eval("\$msg = \"$msg\";");
//             $this->end(false, $msg, '',true,true);
			kernel::single('base_rpc_service')->send_user_error('order_error', $msg);
		}

		$obj_dlytype = $this->app->model('dlytype');
		if ($_POST['payment']['pay_app_id'] == '-1')
		{
			$arr_dlytype = $obj_dlytype->dump($_POST['delivery']['shipping_id'], '*');
			if ($arr_dlytype['has_cod'] == 'false')
			{
//                 $this->end(false, $this->app->_("ship_method_consistent_error"),'',true,true);
				kernel::single('base_rpc_service')->send_user_error('order_error', 'ship_method_consistent_error');
			}
		}

		$obj_filter = kernel::single('b2c_site_filter');
		$_POST = $obj_filter->check_input($_POST);
		$order = $this->app->model('orders');
		$_POST['order_id'] = $order_id = $order->gen_id();

		$_POST['member_id'] = $arrMember['member_id'] ? $arrMember['member_id'] : 0;
		$order_data = array();
		$obj_order_create = kernel::single("b2c_order_create");
		// 加入订单能否生成的判断
		$obj_checkorder = kernel::service('b2c_order_apps', array('content_path'=>'b2c_order_checkorder'));
		if ($obj_checkorder)
		{
			if (!$obj_checkorder->check_create($aCart, $_POST['delivery']['ship_area'], $message))
//                 $this->end(false, $message);
				kernel::single('base_rpc_service')->send_user_error('order_error', $message);
		}
		$order_data = $obj_order_create->generate($_POST,'',$msg,$aCart);
		$obj_checkproducts = kernel::servicelist('b2c_order_check_products');
		if ($obj_checkproducts)
		{
			foreach($obj_checkproducts as $obj_check){
				if (!$obj_check->check_products($order_data, $messages))
//                     $this->end(false, $messages);
					kernel::single('base_rpc_service')->send_user_error('order_error', $message);
			}
		}
		if (!$order_data || !$order_data['order_objects'])
		{
			$db->rollback();
//             $this->end(false, $msg, $this->gen_url(array('app'=>'b2c','ctl'=>'site_cart','act'=>'checkout')),true,true);
			kernel::single('base_rpc_service')->send_user_error('order_error', $msg);
		}


		if(isset($_POST['r_time']) && trim($_POST['r_time']) !='')
			$order_data['consignee']['r_time'] = trim($_POST['r_time']); //送货\自提时间

		//所属仓库门店
		if(isset($_POST['branch_id']) && intval($_POST['branch_id']) > 0){
			$order_data['branch_id'] = intval($_POST['branch_id']);
			$branch_mdl = kernel::single("ome_mdl_branch");
			if($branch_mdl){
				$branch_obj = $branch_mdl->dump(array('branch_id'=>$order_data['branch_id']));
				$order_data['branch_name_user'] = $branch_obj['name'];
			}
		}

		//收货人身份证
		$member_addrs_info = app::get('b2c')->model('member_addrs')->dump($address['addr_id']);
		$order_data['cardnum'] = $address['cardnum'];
		if(!$member_addrs_info){
			$db->rollback();
			kernel::single('base_rpc_service')->send_user_error('order_error', '收货地址错误');
		}else{
			$order_data['cardnum']=$member_addrs_info['card_num'];
		}
		// if(trim($order_data['cardnum']) == ''){
		//     $db->rollback();
		//     kernel::single('base_rpc_service')->send_user_error('order_error', '身份证号码不能为空');
		// }
		//end 收货人身份证

		$result = $obj_order_create->save($order_data, $msg);
		if ($result)
		{
			// 发票高级配置埋点
			foreach( kernel::servicelist('invoice_setting') as $services ) {
				if ( is_object($services) ) {
					if ( method_exists($services, 'saveInvoiceData') ) {
						$services->saveInvoiceData($_POST['order_id'],$_POST['payment']);
					}
				}
			}
			// 与中心交互
			$is_need_rpc = false;
			$obj_rpc_obj_rpc_request_service = kernel::servicelist('b2c.rpc_notify_request');
			foreach ($obj_rpc_obj_rpc_request_service as $obj)
			{
				if ($obj && method_exists($obj, 'rpc_judge_send'))
				{
					if ($obj instanceof b2c_api_rpc_notify_interface)
						$is_need_rpc = $obj->rpc_judge_send($order_data);
				}

				if ($is_need_rpc) break;
			}

			if ($is_need_rpc)
			{
			  /*
				$obj_rpc_request_service = kernel::service('b2c.rpc.send.request');

				if ($obj_rpc_request_service && method_exists($obj_rpc_request_service, 'rpc_caller_request'))
				{
					if ($obj_rpc_request_service instanceof b2c_api_rpc_request_interface)
						$obj_rpc_request_service->rpc_caller_request($order_data,'create');
				}
				else
				{
					$obj_order_create->rpc_caller_request($order_data);
					}*/
			  //新的版本控制api
			  $obj_apiv = kernel::single('b2c_apiv_exchanges_request');
			  $obj_apiv->rpc_caller_request($order_data, 'ordercreate');
			}
		}

		// 取到日志模块
		if ($arrMember['member_id'])
		{
			$obj_members = $this->app->model('members');
			$arrPams['pam_account']['login_name'] = $arrMember['uname'];
		}

		// remark create
		$obj_order_create = kernel::single("b2c_order_remark");
		$arr_remark = array(
			'order_bn' => $order_id,
			'mark_text' => $_POST['memo'],
			'op_name' => (!$arrMember['member_id']) ? app::get('b2c')->_('顾客') : $arrPams['pam_account']['login_name'],
			'mark_type' => 'b0',
		);

		$log_text = "";
		if ($result)
		{
			$log_text[] = array(
				'txt_key'=>'订单创建成功！',
				'data'=>array(
				),
			);
			$log_text = serialize($log_text);
		}
		else
		{
			$log_text[] = array(
				'txt_key'=>'订单创建失败！',
				'data'=>array(
				),
			);
			$log_text = serialize($log_text);
		}
		$orderLog = $this->app->model("order_log");
		$sdf_order_log = array(
			'rel_id' => $order_id,
			'op_id' => $arrMember['member_id'],
			'op_name' => (!$arrMember['member_id']) ? app::get('b2c')->_('顾客') : $arrPams['pam_account']['login_name'],
			'alttime' => time(),
			'bill_type' => 'order',
			'behavior' => 'creates',
			'result' => 'SUCCESS',
			'log_text' => $log_text,
		);

		$log_id = $orderLog->save($sdf_order_log);

		if ($result)
		{
			foreach(kernel::servicelist('b2c_save_post_om') as $object)
			{
				$object->set_arr($order_id, 'order');
			}

			// 设定优惠券不可以使用
			if (isset($aCart['object']['coupon']) && $aCart['object']['coupon'])
			{
				$obj_coupon = kernel::single("b2c_coupon_mem");
				foreach ($aCart['object']['coupon'] as $coupons)
				{
					if($coupons['used'])
						$obj_coupon->use_c($coupons['coupon'], $arrMember['member_id']);
				}
			}

			// 订单成功后清除购物车的的信息
			$this->cart_model = $this->app->model('cart_objects');
			$this->cart_model->remove_object('',null,$mag,$is_fastbuy);

			// 生成cookie有效性的验证信息
			setcookie('ST_ShopEx-Order-Buy', md5($this->app->getConf('certificate.token').$order_id));
			setcookie("purchase[addr][usable]", "", time() - 3600, kernel::base_url().'/');
			setcookie("purchase[shipping]", "", time() - 3600, kernel::base_url().'/');
			setcookie("purchase[payment]", "", time() - 3600, kernel::base_url().'/');
			setcookie("checkout_b2c_goods_buy_info", "", time() - 3600, kernel::base_url().'/');

			// 得到物流公司名称
			if ($order_data['order_objects'])
			{
				$itemNum = 0;
				$good_id = "";
				$goods_name = "";
				foreach ($order_data['order_objects'] as $arr_objects)
				{
					if ($arr_objects['order_items'])
					{
						if ($arr_objects['obj_type'] == 'goods')
						{
							$obj_goods = $this->app->model('goods');
							$good_id = $arr_objects['order_items'][0]['goods_id'];
							$obj_goods->updateRank($good_id, 'buy_count',$arr_objects['order_items'][0]['quantity']);
							$arr_goods = $obj_goods->parent_getList('image_default_id',array('goods_id'=>$good_id));
							$arr_goods = $arr_goods[0];
						}

						foreach ($arr_objects['order_items'] as $arr_items)
						{
							$itemNum = $this->objMath->number_plus(array($itemNum, $arr_items['quantity']));
							if ($arr_objects['obj_type'] == 'goods')
							{
								if ($arr_items['item_type'] == 'product')
									$goods_name .= $arr_items['name'] . ($arr_items['products']['spec_info'] ? '(' . $arr_items['products']['spec_info'] . ')' : '') . '(' . $arr_items['quantity'] . ')';
							}
						}
					}
				}
				$arr_dlytype = $obj_dlytype->dump($order_data['shipping']['shipping_id'], 'dt_name');
				$arr_updates = array(
					'order_id' => $order_id,
					'total_amount' => $order_data['total_amount'],
					'shipping_id' => $arr_dlytype['dt_name'],
					'ship_mobile' => $order_data['consignee']['mobile'],
					'ship_tel' => $order_data['consignee']['telephone'],
					'ship_addr' => $order_data['consignee']['addr'],
					'ship_email' => $order_data['consignee']['email'] ? $order_data['consignee']['email'] : '',
					'ship_zip' => $order_data['consignee']['zip'],
					'ship_name' => $order_data['consignee']['name'],
					'member_id' => $order_data['member_id'] ? $order_data['member_id'] : 0,
					'uname' => (!$order_data['member_id']) ? app::get('b2c')->_('顾客') : $arrPams['pam_account']['login_name'],
					'itemnum' => count($order_data['order_objects']),
					'goods_id' => $good_id,
					'goods_url' => kernel::base_url(1).kernel::url_prefix(),//$this->gen_url(array('app'=>'b2c','ctl'=>'site_product','act'=>'index','arg0'=>$good_id)),
					'thumbnail_pic' => base_storager::image_path($arr_goods['image_default_id']),
					'goods_name' => $goods_name,
					'ship_status' => '',
					'pay_status' => 'Nopay',
					'is_frontend' => true,
				);
				$order->fireEvent('create', $arr_updates, $order_data['member_id']);
			}

			$db->commit($transaction_status);

			/** 订单创建结束后执行的方法 **/
			$odr_create_service = kernel::servicelist('b2c_order.create');
			$arr_order_create_after = array();
			if ($odr_create_service)
			{
				foreach ($odr_create_service as $odr_ser)
				{
					if(!is_object($odr_ser)) continue;

					if( method_exists($odr_ser,'get_order') )
						$index = $odr_ser->get_order();
					else $index = 10;

					while(true) {
						if( !isset($arr_order_create_after[$index]) )break;
						$index++;
					}
					$arr_order_create_after[$index] = $odr_ser;
				}
			}
			ksort($arr_order_create_after);
			if ($arr_order_create_after)
			{
				foreach ($arr_order_create_after as $obj)
				{
					$obj->generate($order_data);
				}
			}
			/** end **/
		}
		else
		{
			$db->rollback();
		}
		if ($_POST['payment']['pay_app_id'] == '-1')
		{
			kernel::single('base_rpc_service')->send_user_success('-1', array('pay_app_id'=>'-1'));
		}
		if ($result)
		{
			$order_num = $order->count(array('member_id' => $order_data['member_id']));
			$obj_mem = $this->app->model('members');
			$obj_mem->update(array('order_num'=>$order_num), array('member_id'=>$order_data['member_id']));
			$order_data['time_now'] = time();
			/** 订单金额为0 **/
			if ($order_data['cur_amount'] == '0')
			{
				// 模拟支付流程
				$objPay = kernel::single("ectools_pay");
				$sdf = array(
					'payment_id' => $objPay->get_payment_id($order_data['order_id']),
					'order_id' => $order_data['order_id'],
					'rel_id' => $order_data['order_id'],
					'op_id' => $order_data['member_id'],
					'pay_app_id' => $order_data['payinfo']['pay_app_id'],
					'currency' => $order_data['currency'],
					'payinfo' => array(
						'cost_payment' => $order_data['payinfo']['cost_payment'],
					),
					'pay_object' => 'order',
					'member_id' => $order_data['member_id'],
					'op_name' => $this->user->user_data['account']['login_name'],
					'status' => 'ready',
					'cur_money' => $order_data['cur_amount'],
					'money' => $order_data['total_amount'],
				);
				$is_payed = $objPay->gopay($sdf, $msg);
				if (!$is_payed){
					$msg = app::get('b2c')->_('订单自动支付失败！');
//                     $this->end(false, $msg, $this->gen_url(array('app'=>'b2c','ctl'=>'site_cart','act'=>'checkout')));
					kernel::single('base_rpc_service')->send_user_error('order_error', $msg);
				}

				$obj_pay_lists = kernel::servicelist("order.pay_finish");
				$is_payed = false;
				foreach ($obj_pay_lists as $order_pay_service_object)
				{
					$is_payed = $order_pay_service_object->order_pay_finish($sdf, 'succ', 'font',$msg);
				}
			}
			return $order_data;
//             $this->end(true, $this->app->_("订单生成成功！"), $this->gen_url(array('app'=>'b2c','ctl'=>'site_paycenter','act'=>'index','arg0'=>$order_id,'arg1'=>'true')),'',true);
		}
		else{

//             $this->end(false, $msg, $this->gen_url(array('app'=>'b2c','ctl'=>'site_cart','act'=>'checkout')),true,true);
			kernel::single('base_rpc_service')->send_user_error('order_error', $msg);
		}
	}

	function select_payment(){
		if($_POST['payment']['currency']){
			$sdf['cur'] = $_POST['payment']['currency'];
		}
		if($_POST['shipping']['shipping_id']){
			$has_cod = app::get('b2c')->model('dlytype')->getList('has_cod',array('dt_id'=>$_POST['shipping']['shipping_id']));
		}
		$obj_payment_select = new ectools_payment_select();
		$currency = app::get('ectools')->model('currency');
		//$this->pagedata['currencys'] = $currency->getList('cur_id,cur_code,cur_name');
		//$this->pagedata['current_currency'] = $sdf['cur'] ? $sdf['cur'] : '';
		//$this->pagedata['app_id'] = 'b2c';//$app_id;
		//$this->pagedata['pay_app_id'] = $_POST['payment']['def_pay']['pay_app_id'];
		//$this->pagedata['payment_html'] = $obj_payment_select->select_pay_method($this,$sdf);
		//echo $this->fetch('site/common/select_payment.html');
		$payments = $obj_payment_select->select_pay_method($this, $sdf, false,false,array('iscommon','iswap'),'API');
		//在预存款页面去掉支付宝支付 2017-08-23  by 马国民
		//先注释掉
		//foreach ($payments as $key => $value) {
		//	if($value['app_class']=='wap_payment_plugin_malipay') unset($payments[$key]);
		//}
		//判断app版本
        $appVersion = $_POST['appVersion'];
        if (!$appVersion) {
			kernel::single('base_rpc_service')->send_user_error('appVersion', '此版本已停用，请下载最新版本');
			return false;
        }
		//2016-6-8 by jeff,去掉索引
		$ret_new = array();
		foreach($payments as & $v) {
			if ($v['app_id']=='wxpayjsapi') {
				continue;
			}
			//如果是新版app，并且app_id是‘微信支付SDK’，过滤掉。by linsuchuan 2018年3月15日 11:14:52
            if ($appVersion && $v['app_id']=='wxpaysdk') {
                continue;
            }
            if (!$appVersion && $v['app_id']=='wxallinpaysdk') {
                continue;
            }
			$ret_new[] = $v;
		}
		return $ret_new;
	}


	function payment_change(){
		$objOrders = $this->app->model('orders');
		$objPay = kernel::single('ectools_pay');
		$objMath = kernel::single('ectools_math');
		$payments = $_POST['payment'];
		$order_id = $_POST['order_id'];
		$currency = $payments['currency'];
		$pay = json_decode($payments['pay_app_id'],true);
		if($pay['pay_app_id'] == -1){
//     		return true;
			kernel::single('base_rpc_service')->send_user_error('pay_app_id_error', '支付ID错误!');
		}
		$arrOrders = $objOrders->dump($order_id,'*');
		if ($arrOrders['payinfo']['pay_app_id'] != $pay['pay_app_id'] || $arrOrders['currency'] != $currency)
		{
			$class_name = "";
			$obj_app_plugins = kernel::servicelist("ectools_payment.ectools_mdl_payment_cfgs");
			foreach ($obj_app_plugins as $obj_app)
			{
				$app_class_name = get_class($obj_app);
				$arr_class_name = explode('_', $app_class_name);
				if (isset($arr_class_name[count($arr_class_name)-1]) && $arr_class_name[count($arr_class_name)-1])
				{
					if ($arr_class_name[count($arr_class_name)-1] == $pay['pay_app_id'])
					{
						$pay_app_ins = $obj_app;
						$class_name = $app_class_name;
					}
				}
				else
				{
					if ($app_class_name == $pay['pay_app_id'])
					{
						$pay_app_ins = $obj_app;
						$class_name = $app_class_name;
					}
				}
			}
			$strPayment = app::get('ectools')->getConf($class_name);
			$arrPayment = unserialize($strPayment);
			$getcur = app::get('ectools')->model('currency')->getcur($currency);
			$arrOrders['currency'] = $getcur['cur_code'];
			$arrOrders['cur_rate'] = $getcur['cur_rate'];
		}

		$cost_payment = $objMath->number_multiple(array($objMath->number_minus(array($objMath->number_minus(array($arrOrders['total_amount'], $arrOrders['payinfo']['cost_payment'])),$arrOrders['payed'])), $arrPayment['setting']['pay_fee']));
		$total_amount = $objMath->number_plus(array($objMath->number_minus(array($arrOrders['total_amount'], $arrOrders['payinfo']['cost_payment'])), $cost_payment));
		$cur_money = $objMath->number_multiple(array($total_amount, $arrOrders['cur_rate']));

		// 更新订单支付信息
		$arr_updates = array(
				'order_id' => $order_id,
				'payinfo' => array(
						'pay_app_id' => $pay['pay_app_id'],
						'cost_payment' => $objMath->number_multiple(array($cost_payment, $arrOrders['cur_rate'])),
				),
				'currency' => $arrOrders['currency'],
				'cur_rate' => $arrOrders['cur_rate'],
				'total_amount' => $total_amount,
				'cur_amount' => $cur_money,
		);

		if($objOrders->save($arr_updates)){
			return $arr_updates;
		}

		kernel::single('base_rpc_service')->send_user_error('update_order_error', '更新支付方式失败!');


	}

	function aa(){
		$member_id = 802;
		return $this->tuisong($member_id);
	}

		function get_token($member_id){
		  //global $temp;






		 $token = app::get('b2c')->model('members')->getList('token',array('member_id'=>$member_id));
		 return $token[0]['token'];
	}






	function tuisong($member_id){


		 $token=$this->get_token($member_id);
		// $token = app::get('b2c')->model('members')->getList('token',array('member_id'=>$this->app->member_id));

		  //return 123;
		  //return XingeApp::PushTokenAndroid(2100090629, "efbbcd11f4186adfe11dda6d1888ac76", "test", "泳兰说要种子！",'d05128ad15092ad34dcd8f1fc77c7b4af8870432');
		  // if(XingeApp::PushTokenIos(2200090632,"e1378270db484874903605fc8b3f3130","你走了美宁跟威雄怎么办",$token,XingeApp::IOSENV_DEV)==0){
		  //   return '123';
		  // }


		 // if ($_COOKIE['atoken']) {
		 //        $token = $_COOKIE['itoken'];
		 //        return XingeApp::PushTokenAndroid(2100090629, "efbbcd11f4186adfe11dda6d1888ac76", "test", "test",'$token');
		 //    }
		 //    elseif ($_COOKIE['itoken']) {
		 //        $token = $_COOKIE['itoken'];
		 //        return XingeApp::PushTokenIos(2200090632,"e1378270db484874903605fc8b3f3130","泳兰走了美宁怎么办",'$token',XingeApp::IOSENV_DEV);


		 //    }
		$push1 = new XingeApp(2200090632, 'e1378270db484874903605fc8b3f3130');
		//$mess1 = new Message();
		$mess1 = new MessageIOS();

		//$mess1->setType(Message::TYPE_MESSAGE);
		 $mess1->setSound("beep.wav");
		 $mess1->setAlert('您又赚钱啦，您有合伙人已下单');
		$mess1->setLoopTimes(1);


		$ret1 = $push1->PushSingleDevice($token, $mess1,XingeApp::IOSENV_DEV);




		$push = new XingeApp(2100090629, 'efbbcd11f4186adfe11dda6d1888ac76');
		$mess = new Message();
		//$mess = new MessageIOS();

		$mess->setType(Message::TYPE_MESSAGE);
		 $mess->setTitle('美丽奇迹');
		 $mess->setContent('您又赚钱啦，您有合伙人已下单');
		$mess->setLoopTimes(1);


		$ret = $push->PushSingleDevice($token, $mess);
	   return $ret;

	}

	public function pushall(){
		 $push1 = new XingeApp(2200090632, 'e1378270db484874903605fc8b3f3130');
		//$mess1 = new Message();
		$mess1 = new MessageIOS();

		//$mess1->setType(Message::TYPE_MESSAGE);
		 $mess1->setSound("beep.wav");
		 $mess1->setAlert('测试，请忽略');
		$mess1->setLoopTimes(1);


		$ret1 = $push1->PushAllDevices(0, $mess1,XingeApp::IOSENV_DEV);

		$push = new XingeApp(2100097297, '695bc3c3070cd38a3790c8ed8032e700');
		$mess = new Message();
		//$mess = new MessageIOS();

		$mess->setType(Message::TYPE_MESSAGE);
		 $mess->setTitle('测试');
		 $mess->setContent('请忽略');
		$mess->setLoopTimes(1);


		$ret = $push->PushAllDevices(0, $mess);
		return $ret1;
	}


 //-----erp api ------
	/**
	 * 订单完成
	 * @params string oder id
	 * @return boolean 成功与否
	 */
	public function dofinish($order_id)
	{
		$order_id = $_POST['order_id'];

		$obj_checkorder = kernel::service('b2c_order_apps', array('content_path'=>'b2c_order_checkorder'));
		if (!$obj_checkorder->check_order_finish($order_id,'',$message))
		{
			kernel::single('base_rpc_service')->send_user_error('finish_check_error', $message);
		}

		$sdf['order_id'] = $order_id;
		$sdf['op_id'] = "1";
		$sdf['opname'] = "erpadmin";

		$objOrder = $this->app->model('orders');

		$b2c_order_finish = kernel::single("b2c_order_finish");
		if ($b2c_order_finish->generate($sdf, $this, $message))
		{
			if($order_object = kernel::service('b2c_order_rpc_async')){
				$order_object->modifyActive($sdf['order_id']);
			}

			//$this->end(true, app::get('b2c')->_('完成订单成功！'));
			return "succ";
		}
		else
		{
			//$this->end(false, app::get('b2c')->_('完成订单失败！'));
			kernel::single('base_rpc_service')->send_user_error('finish_error', "完成订单失败！");
		}
	}

	/**
	 * 订单详情查询
	 *
	 * @params string oder_id 订单ID
	 *
	 * @return array data todo 请增加返回数据说明
	 *
	 * @author todo 在已有的源文件中增加方法，请记得加上author信息
	 */
	public function info() {
		$order_id = $_POST['order_id'];
		if(!isset($order_id) || !$order_id){
			kernel::single('base_rpc_service')->send_user_error('select_error', "订单编号不能为空！");
		}

		$objOrder = app::get('b2c')->model('orders');
		$subsdf = array('order_objects'=>array('*',array('order_items'=>array('*',array(':products'=>'*')))), 'order_pmt'=>array('*'));
		$sdf_order = $objOrder->dump($order_id, '*', $subsdf);

		if(!$sdf_order||$this->app->member_id!=$sdf_order['member_id']){
			$this->app->rpcService->send_user_error('404', '订单号：'.$order_id.'不存在！');
		}

		// 处理收货人地区
		$arr_consignee_area = array();
		$arr_consignee_regions = array();
		if (strpos($sdf_order['consignee']['area'], ':') !== false)
		{
			$arr_consignee_area = explode(':', $sdf_order['consignee']['area']);
			if ($arr_consignee_area[1])
			{
				if (strpos($arr_consignee_area[1], '/') !== false)
				{
					$arr_consignee_regions = explode('/', $arr_consignee_area[1]);
				}
			}

			$sdf_order['consignee']['area'] = (is_array($arr_consignee_regions) && $arr_consignee_regions) ? $arr_consignee_regions[0] . $arr_consignee_regions[1] . $arr_consignee_regions[2] : $sdf_order['consignee']['area'];
		}

		$data['order'] = $sdf_order;

		// 订单留言.
		$oMsg = kernel::single("b2c_message_order");
		$arrOrderMsg = $oMsg->getList('*', array('order_id' => $order_id, 'object_type' => 'order'), $offset=0, $limit=-1, 'time DESC');

		$data['ordermsg'] = $arrOrderMsg;

		// 支付单信息
		$obj_payments = app::get('ectools')->model('payments');
		$data['order']['payments'] = $obj_payments->get_payments_by_order_id($order_id);

		//获取时间
		$data['time_now'] = time();

		return $data;

		// todo 请去掉废弃代码
		/* $tmp_order = array();
		$tmp_order = kernel::single('b2c_mdl_orders')
			->getRow(
				'*',
				array('order_id'=>$order_id)
			);
		return !$tmp_order ? kernel::single('base_rpc_service')->send_user_error('select_error', "查询失败") : $tmp_order; */
	}

}

